import React, { useEffect, useState, useCallback } from "react";
import {
  Space,
  Table,
  Form,
  Input,
  Button,
  Select,
  Popconfirm,
  message,
  Modal,
} from "antd";
import type { TableProps } from "antd";
import { CaretRightOutlined } from "@ant-design/icons";
import { get, del, put, post } from "../../../api/request";
import useBtns from "../../../hooks/useBtns";
import * as XLSX from "xlsx";
import { useNavigate } from "react-router-dom";

// 添加表格样式 - 支持主题切换
const tableStyles = `
  /* 浅色主题样式 */
  [data-theme="light"] .table-row-light {
    background-color: #fafafa;
  }
  [data-theme="light"] .table-row-dark {
    background-color: #ffffff;
  }
  [data-theme="light"] .table-row-light:hover,
  [data-theme="light"] .table-row-dark:hover {
    background-color: #e6f7ff !important;
  }
  [data-theme="light"] .ant-table-thead > tr > th {
    background-color: #f5f5f5 !important;
    font-weight: 600 !important;
    color: #333 !important;
    border-bottom: 1px solid #e5e5e5 !important;
  }
  [data-theme="light"] .ant-table-tbody > tr > td {
    border-bottom: 1px solid #f0f0f0 !important;
    color: #333 !important;
  }
  [data-theme="light"] .ant-table-tbody > tr:hover > td {
    background-color: #e6f7ff !important;
  }
  
  /* 深色主题样式 */
  [data-theme="dark"] .table-row-light {
    background-color: #1f1f1f;
  }
  [data-theme="dark"] .table-row-dark {
    background-color: #262626;
  }
  [data-theme="dark"] .table-row-light:hover,
  [data-theme="dark"] .table-row-dark:hover {
    background-color: #177ddc !important;
  }
  [data-theme="dark"] .ant-table-thead > tr > th {
    background-color: #141414 !important;
    font-weight: 600 !important;
    color: #fff !important;
    border-bottom: 1px solid #303030 !important;
  }
  [data-theme="dark"] .ant-table-tbody > tr > td {
    border-bottom: 1px solid #303030 !important;
    color: #fff !important;
  }
  [data-theme="dark"] .ant-table-tbody > tr:hover > td {
    background-color: #177ddc !important;
  }
  
  /* 表格标题样式增强 */
  .ant-table-thead > tr > th {
    transition: all 0.3s ease !important;
    position: relative !important;
  }
  
  /* 表格标题悬停效果 */
  .ant-table-thead > tr > th:hover {
    background-color: var(--table-header-hover-bg, #e6f7ff) !important;
  }
  
  /* 表格边框样式 */
  .ant-table {
    border-radius: 8px !important;
    overflow: hidden !important;
    box-shadow: var(--table-shadow, 0 2px 8px rgba(0,0,0,0.1)) !important;
  }
  
  /* 分页器样式 */
  .ant-pagination {
    margin-top: 16px !important;
    text-align: center !important;
  }
  
  /* 表格内容区域样式 */
  .ant-table-content {
    border-radius: 8px !important;
  }
`;

// 注入样式
if (typeof document !== 'undefined') {
  const styleElement = document.createElement('style');
  styleElement.textContent = tableStyles;
  document.head.appendChild(styleElement);
}

// 定义Axios错误类型
interface AxiosError {
  response?: {
    data?: unknown;
    status?: number;
  };
  message?: string;
}

interface ShopType {
  id: string;
  shopName: string;
  shopType: string;
  shopTel: string;
  shopAddress: string;
  shopDescription: string;
  shopScore: string;
  shopSellCount: string;
  shopImage?: string;
}

const typeOptions = [
  { label: "生鲜", value: "生鲜" },
  { label: "水果", value: "水果" },
  { label: "冷饮", value: "冷饮" },
  { label: "甜品", value: "甜品" },
  { label: "鲜花", value: "鲜花" },
];

const Indexone: React.FC = () => {
  const nav=useNavigate()
  const [data, setData] = useState<ShopType[]>([]);
  const [pageCode, setPageCode] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalCount, setTotalCount] = useState(0);
  const [modal, setModal] = useState({
    open: false,
    title: "",
    record: null as ShopType | null,
  });
  const [searchForm] = Form.useForm();
  const [editForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const dele = useBtns("del");
  const edit = useBtns("edit");
  const add = useBtns("add");
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  // 检测主题变化
  useEffect(() => {
    // 从本地存储获取主题模式
    const savedTheme = localStorage.getItem('themeMode') || 'light';
    document.documentElement.setAttribute('data-theme', savedTheme);
    
    // 监听主题变化
    const handleThemeChange = () => {
      const currentTheme = localStorage.getItem('themeMode') || 'light';
      document.documentElement.setAttribute('data-theme', currentTheme);
    };
    
    // 监听storage事件（跨标签页同步）
    window.addEventListener('storage', handleThemeChange);
    
    // 监听DOM变化（同标签页内切换）
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.type === 'attributes' && mutation.attributeName === 'data-theme') {
          const newTheme = document.documentElement.getAttribute('data-theme') || 'light';
          localStorage.setItem('themeMode', newTheme);
        }
      });
    });
    
    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ['data-theme']
    });
    
    return () => {
      window.removeEventListener('storage', handleThemeChange);
      observer.disconnect();
    };
  }, []);

  const fetchData = useCallback(
    async (params = {}) => {
      setLoading(true);
      try {
        const values = searchForm.getFieldsValue();
        const res = await get("/list", {
          pageCode,
          pageSize,
          ...values,
          ...params,
        });
        setData(res.data.data.data);
        setTotalCount(res.data.data.totalCount);
      } finally {
        setLoading(false);
      }
    },
    [pageCode, pageSize, searchForm]
  );

  useEffect(() => {
    fetchData();
  }, [pageCode, pageSize, fetchData]);

  const handleDelete = async (record: ShopType) => {
    try {
      await del("/list", { id: record.id });
      message.success("删除成功");
      fetchData();
    } catch {
      message.error("删除失败");
    }
  };

  const handleModalOk = async () => {
    try {
      const values = editForm.getFieldsValue();
      console.log('提交的数据:', values); // 调试用
      console.log('模态框标题:', modal.title); // 调试用
      console.log('当前图片预览:', imagePreview); // 调试用
      
      // 确保所有字段都有有效值，避免undefined或null
      const cleanValues = {
        shopName: values.shopName || '',
        shopType: values.shopType || '',
        shopTel: values.shopTel || '',
        shopAddress: values.shopAddress || '',
        shopDescription: values.shopDescription || '',
        shopScore: values.shopScore || '5',
        shopSellCount: values.shopSellCount || '0',
        shopImage: imagePreview || values.shopImage || ''
      };
      
      // 详细检查每个字段
      console.log('原始表单数据:', values);
      console.log('清理后的数据:', cleanValues);
      console.log('字段检查:');
      console.log('- shopName:', typeof values.shopName, values.shopName);
      console.log('- shopType:', typeof values.shopType, values.shopType);
      console.log('- shopTel:', typeof values.shopTel, values.shopTel);
      console.log('- shopAddress:', typeof values.shopAddress, values.shopAddress);
      console.log('- shopDescription:', typeof values.shopDescription, values.shopDescription);
      console.log('- shopScore:', typeof values.shopScore, values.shopScore);
      console.log('- shopSellCount:', typeof values.shopSellCount, values.shopSellCount);
      console.log('- shopImage:', typeof values.shopImage, values.shopImage);
      console.log('- imagePreview:', typeof imagePreview, imagePreview);
      
      // 检查是否有任何字段仍然是undefined或null
      const invalidFields = Object.entries(cleanValues).filter(([, value]) => 
        value === undefined || value === null
      );
      
      if (invalidFields.length > 0) {
        console.error('发现无效字段:', invalidFields);
        message.error(`发现无效字段: ${invalidFields.map(([key]) => key).join(', ')}`);
        return;
      }
      
      if (modal.title === "add") {
        console.log('执行新增操作'); // 调试用
        console.log('请求URL: /api/list'); // 调试用
        console.log('请求方法: POST'); // 调试用
        console.log('请求数据:', JSON.stringify(cleanValues, null, 2)); // 调试用
        
        const response = await put("/list", cleanValues);
        console.log('服务器响应:', response); // 调试用
        message.success("新增成功");
      } else if (modal.title === "edit" && modal.record) {
        console.log('执行编辑操作'); // 调试用
        console.log('请求URL: /api/list'); // 调试用
        console.log('请求方法: PUT'); // 调试用
        console.log('请求数据:', JSON.stringify({ ...cleanValues, id: modal.record.id }, null, 2)); // 调试用
        
        const response = await post("/list", { ...cleanValues, id: modal.record.id });
        console.log('服务器响应:', response); // 调试用
        message.success("编辑成功");
      }
      setModal({ ...modal, open: false });
      setImagePreview(null); // 清空图片预览
      fetchData();
    } catch (error: unknown) {
      console.error('操作失败详细信息:', error); // 调试用
      
      // 类型安全的错误处理
      const axiosError = error as AxiosError;
      console.log('错误响应数据:', axiosError.response?.data); // 调试用
      console.error('错误状态码:', axiosError.response?.status); // 调试用
      console.error('错误消息:', axiosError.message); // 调试用
      
      // 输出更详细的错误信息
      if (axiosError.response?.data) {
        console.error('服务器错误详情:', JSON.stringify(axiosError.response.data, null, 2));
      }
      
      // 根据错误类型显示不同的错误信息
      if (axiosError.response?.status === 500) {
        message.error("服务器内部错误，请检查后端服务");
      } else if (axiosError.response?.status === 400) {
        message.error("请求参数错误，请检查输入数据");
      } else if (axiosError.response?.status === 404) {
        message.error("API接口不存在，请检查接口地址");
      } else {
        message.error(`操作失败: ${axiosError.message || '未知错误'}`);
      }
    }
  };



  const removeImage = () => {
    setImagePreview(null);
    editForm.setFieldValue('shopImage', '');
    message.success('图片已移除');
  };

  const openModal = (title: string, record?: ShopType) => {
    setModal({ open: true, title, record: record || null });
    if (record) {
      editForm.setFieldsValue(record);
      setImagePreview(record.shopImage || null);
    } else {
      editForm.resetFields();
      setImagePreview(null);
    }
  };

  // 批量删除函数
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的数据');
      return;
    }
    Modal.confirm({
      title: '批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 条数据吗？删除后无法恢复！`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          // 支持后端批量接口可一次性提交，否则循环调用
          for (const id of selectedRowKeys) {
            await del('/list', { id });
          }
          message.success('批量删除成功');
          setSelectedRowKeys([]);
          fetchData();
        } catch {
          message.error('批量删除失败');
        }
      }
    });
  };

  const columns: TableProps<ShopType>["columns"] = [
    { 
      title: "ID", 
      dataIndex: "id", 
      key: "id",
      width: 120,
      ellipsis: true,
      render: (id: string) => (
        <span style={{ 
          fontFamily: 'monospace', 
          fontSize: '12px',
          color: '#666'
        }}>
          {id}
        </span>
      )
    },
    { 
      title: "名称", 
      dataIndex: "shopName", 
      key: "shopName",
      width: 150,
      ellipsis: true,
      render: (name: string) => (
        <span style={{ 
          fontWeight: 500,
          color: '#1890ff'
        }}>
          {name}
        </span>
      )
    },
    { 
      title: "类型", 
      dataIndex: "shopType", 
      key: "shopType",
      width: 100,
      render: (type: string) => {
        const typeColors = {
          '生鲜': '#52c41a',
          '水果': '#fa8c16',
          '冷饮': '#1890ff',
          '甜品': '#eb2f96',
          '鲜花': '#722ed1'
        };
        return (
          <span style={{
            padding: '4px 8px',
            borderRadius: '12px',
            fontSize: '12px',
            backgroundColor: typeColors[type as keyof typeof typeColors] || '#d9d9d9',
            color: 'white',
            fontWeight: 500
          }}>
            {type}
          </span>
        );
      }
    },
    { 
      title: "手机号", 
      dataIndex: "shopTel", 
      key: "shopTel",
      width: 130,
      ellipsis: true,
      render: (tel: string) => (
        <span style={{ 
          fontFamily: 'monospace',
          color: '#666'
        }}>
          {tel}
        </span>
      )
    },
    { 
      title: "地址", 
      dataIndex: "shopAddress", 
      key: "shopAddress",
      width: 200,
      ellipsis: true,
      render: (address: string) => (
        <span style={{ 
          color: '#666',
          fontSize: '13px'
        }}>
          {address}
        </span>
      )
    },
    { 
      title: "描述", 
      dataIndex: "shopDescription", 
      key: "shopDescription",
      width: 200,
      ellipsis: true,
      render: (desc: string) => (
        <span style={{ 
          color: '#666',
          fontSize: '13px'
        }}>
          {desc}
        </span>
      )
    },
    { 
      title: "评分", 
      dataIndex: "shopScore", 
      key: "shopScore",
      width: 120,
      align: 'center' as const,
      render: (score: string) => <StarRating score={score} size={18} />
    },
    { 
      title: "销售量", 
      dataIndex: "shopSellCount", 
      key: "shopSellCount",
      width: 100,
      align: 'center' as const,
      render: (count: string) => (
        <span style={{
          padding: '2px 6px',
          borderRadius: '8px',
          backgroundColor: '#f6ffed',
          color: '#52c41a',
          fontSize: '12px',
          fontWeight: 500
        }}>
          {count}
        </span>
      )
    },
    {
      title: "图片",
      dataIndex: "shopImage",
      key: "shopImage",
      width: 80,
      align: 'center' as const,
      render: (imageUrl: string, record: ShopType) => {
        console.log('渲染图片列:', { imageUrl, recordId: record.id }); // 调试用
        return (
          imageUrl ? (
            <img 
              src={imageUrl} 
              alt="商铺图片" 
              style={{ 
                width: 50, 
                height: 50, 
                objectFit: 'cover',
                borderRadius: '8px',
                cursor: 'pointer',
                border: '2px solid #f0f0f0',
                transition: 'all 0.2s ease'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = 'scale(1.1)';
                e.currentTarget.style.borderColor = '#1890ff';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = 'scale(1)';
                e.currentTarget.style.borderColor = '#f0f0f0';
              }}
              onClick={() => {
                Modal.info({
                  title: '商铺图片',
                  content: (
                    <img 
                      src={imageUrl} 
                      alt="商铺图片" 
                      style={{ 
                        width: '100%', 
                        maxHeight: '400px',
                        objectFit: 'contain'
                      }}
                    />
                  ),
                  width: 600,
                });
              }}
            />
          ) : (
            <span style={{ 
              color: '#999',
              fontSize: '12px',
              fontStyle: 'italic'
            }}>
              无图片
            </span>
          )
        );
      },
    },
    {
      title: "操作",
      key: "action",
      width: 150,
      align: 'center' as const,
      fixed: 'right' as const,
      render: (_, record) => (
        <Space size="small">
          {edit && (
            <Button 
              type="primary" 
              size="small"
              onClick={() => openModal("edit", record)}
              style={{
                borderRadius: '6px',
                fontSize: '12px',
                height: '28px',
                padding: '0 12px'
              }}
            >
              编辑
            </Button>
          )}
          <Popconfirm
            title="确定要删除这条数据吗？"
            description="删除后无法恢复，请谨慎操作"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
            placement="top"
          >
            {dele && (
              <Button 
                danger 
                size="small"
                style={{
                  borderRadius: '6px',
                  fontSize: '12px',
                  height: '28px',
                  padding: '0 12px'
                }}
              >
                删除
              </Button>
            )}
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 星星评分组件
  const StarRating = ({ score, size = 16 }: { score: string | number, size?: number }) => {
    const scoreNum = typeof score === 'string' ? parseInt(score) : score;
    const validScore = scoreNum || 0;
    
    return (
      <span style={{ 
        color: '#FFD700', 
        fontSize: `${size}px`,
        display: 'inline-flex',
        alignItems: 'center',
        gap: '2px'
      }}>
        {Array.from({ length: 5 }, (_, index) => (
          <span key={index} style={{ 
            opacity: index < validScore ? 1 : 0.3,
            transition: 'opacity 0.2s ease'
          }}>
            {index < validScore ? '⭐' : '☆'}
          </span>
        ))}
      </span>
    );
  };

  return (
    <div>
      <Form form={searchForm} layout="inline" style={{ marginBottom: 16 }}>
        <Form.Item name="searchValue" label="关键词">
          <Input
            placeholder="请输入ID/名称/手机号"
            allowClear
            style={{ width: 180 }}
          />
        </Form.Item>
        <Form.Item name="type" label="类型">
          <Select
            placeholder="请选择类型"
            allowClear
            style={{ width: 140 }}
            options={typeOptions}
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button
              type="primary"
              onClick={() => {
                setPageCode(1);
                fetchData({ pageCode: 1 });
              }}
            >
              搜索
            </Button>
            <Button
              onClick={() => {
                searchForm.resetFields();
                setPageCode(1);
                fetchData({ pageCode: 1 });
              }}
            >
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>
      {add && (
        <Button
          type="primary"
          style={{ marginBottom: 16, marginRight: 8 }}
          onClick={() => openModal("add")}
        >
          新增
        </Button>
      )}
      <Button
        onClick={() => {
          // 导出Excel逻辑
          const exportData = data.map(
            ({
              id,
              shopName,
              shopType,
              shopTel,
              shopAddress,
              shopDescription,
              shopScore,
              shopSellCount,
              shopImage,
            }) => ({
              ID: id,
              名称: shopName,
              类型: shopType,
              手机号: shopTel,
              地址: shopAddress,
              描述: shopDescription,
              评分: '⭐'.repeat(parseInt(shopScore) || 0),
              销售量: shopSellCount,
              图片: shopImage ? '有图片' : '无图片',
            })
          );
          const ws = XLSX.utils.json_to_sheet(exportData);
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
          XLSX.writeFile(wb, "商铺信息.xlsx");
        }}
        style={{ marginBottom: 16 }}
      >
        导出Excel
      </Button>
      <Button style={{ marginBottom: 16, marginLeft: 8 }} onClick={()=>nav('/indextow')}>
        <CaretRightOutlined />
      </Button>
      {/* 在工具栏添加批量删除按钮 */}
      <Button
        danger
        disabled={selectedRowKeys.length === 0}
        style={{ marginBottom: 16, marginLeft: 8 }}
        onClick={handleBatchDelete}
      >
        批量删除
      </Button>
      
      {/* 表格工具栏 */}
      <div style={{ 
        marginBottom: 16, 
        padding: '16px 20px',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        borderRadius: '12px',
        border: 'none',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        boxShadow: '0 4px 15px rgba(102, 126, 234, 0.3)',
        color: 'white'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px', flexWrap: 'wrap' }}>
          <div style={{ 
            display: 'flex', 
            alignItems: 'center', 
            gap: '8px',
            padding: '8px 12px',
            backgroundColor: 'rgba(255, 255, 255, 0.1)',
            borderRadius: '8px',
            backdropFilter: 'blur(10px)'
          }}>
            <span style={{ fontWeight: 600, fontSize: '14px' }}>📊 数据统计</span>
            <span style={{ 
              color: '#FFD700', 
              fontWeight: 600,
              fontSize: '16px'
            }}>
              共 {totalCount} 条记录
            </span>
          </div>
          
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap' }}>
            {[
              { type: '生鲜', icon: '🥬' },
              { type: '水果', icon: '🍎' },
              { type: '冷饮', icon: '🥤' },
              { type: '甜品', icon: '🍰' },
              { type: '鲜花', icon: '🌸' }
            ].map(({ type, icon }) => (
              <div key={type} style={{
                display: 'flex',
                alignItems: 'center',
                gap: '4px',
                padding: '6px 10px',
                backgroundColor: 'rgba(255, 255, 255, 0.15)',
                borderRadius: '20px',
                fontSize: '12px',
                fontWeight: 500,
                backdropFilter: 'blur(10px)',
                border: '1px solid rgba(255, 255, 255, 0.2)'
              }}>
                <span style={{ fontSize: '14px' }}>{icon}</span>
                <span>{type}: {data.filter(item => item.shopType === type).length}</span>
              </div>
            ))}
          </div>
        </div>
        
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <Button 
            size="small" 
            type="primary"
            ghost
            onClick={() => {
              const avgScore = data.reduce((sum, item) => sum + parseInt(item.shopScore || '0'), 0) / data.length;
              Modal.info({
                title: '📈 数据统计',
                content: (
                  <div style={{ textAlign: 'center', padding: '20px 0' }}>
                    <div style={{ fontSize: '24px', color: '#1890ff', marginBottom: '10px' }}>
                      {avgScore.toFixed(1)} ⭐
                    </div>
                    <div style={{ color: '#666' }}>平均评分</div>
                  </div>
                ),
                width: 300,
                centered: true
              });
            }}
            style={{
              borderRadius: '20px',
              border: '1px solid rgba(255, 255, 255, 0.3)',
              color: 'white',
              fontWeight: 500
            }}
          >
            📊 平均评分
          </Button>
          <Button 
            size="small" 
            type="primary"
            ghost
            onClick={() => {
              const totalSales = data.reduce((sum, item) => sum + parseInt(item.shopSellCount || '0'), 0);
              const avgSales = totalSales / data.length;
              Modal.info({
                title: '💰 销售统计',
                content: (
                  <div style={{ textAlign: 'center', padding: '20px 0' }}>
                    <div style={{ fontSize: '24px', color: '#52c41a', marginBottom: '10px' }}>
                      {totalSales.toLocaleString()}
                    </div>
                    <div style={{ color: '#666', marginBottom: '10px' }}>总销售量</div>
                    <div style={{ fontSize: '16px', color: '#fa8c16' }}>
                      平均: {avgSales.toFixed(0)}
                    </div>
                  </div>
                ),
                width: 300,
                centered: true
              });
            }}
            style={{
              borderRadius: '20px',
              border: '1px solid rgba(255, 255, 255, 0.3)',
              color: 'white',
              fontWeight: 500
            }}
          >
            💰 销售统计
          </Button>
          <Button 
            size="small" 
            type="primary"
            ghost
            onClick={() => {
              const scoreDistribution = [1, 2, 3, 4, 5].map(score => ({
                score,
                count: data.filter(item => parseInt(item.shopScore || '0') === score).length
              }));
              
              Modal.info({
                title: '⭐ 评分分布',
                content: (
                  <div style={{ padding: '20px 0' }}>
                    {scoreDistribution.map(({ score, count }) => (
                      <div key={score} style={{
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        padding: '8px 0',
                        borderBottom: '1px solid #f0f0f0'
                      }}>
                        <span>{'⭐'.repeat(score)}</span>
                        <span style={{ color: '#1890ff', fontWeight: 500 }}>{count} 家</span>
                      </div>
                    ))}
                  </div>
                ),
                width: 300,
                centered: true
              });
            }}
            style={{
              borderRadius: '20px',
              border: '1px solid rgba(255, 255, 255, 0.3)',
              color: 'white',
              fontWeight: 500
            }}
          >
            ⭐ 评分分布
          </Button>
        </div>
      </div>
      
      <Table
        columns={columns}
        rowKey="id"
        dataSource={data}
        rowSelection={rowSelection}
        loading={loading}
        pagination={{
          current: pageCode,
          pageSize,
          total: totalCount,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
          onChange: (page, size) => {
            setPageCode(page);
            setPageSize(size);
          },
        }}
        scroll={{ x: 1200, y: 500 }}
        size="middle"
        bordered
        rowClassName={(record, index) => 
          index % 2 === 0 ? 'table-row-light' : 'table-row-dark'
        }
        onRow={(record) => ({
          onClick: () => {
            console.log('点击行:', record);
          },
          style: {
            cursor: 'pointer',
            transition: 'background-color 0.2s ease'
          }
        })}
        style={{
          borderRadius: '8px',
          overflow: 'hidden',
          boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)'
        }}
      />
      <Modal
        title={modal.title === "edit" ? "编辑" : "新增"}
        open={modal.open}
        onOk={handleModalOk}
        onCancel={() => {
          setModal({ ...modal, open: false });
          setImagePreview(null);
          editForm.resetFields();
        }}
        destroyOnClose
      >
        <Form form={editForm} layout="vertical">
          <Form.Item
            label="名称"
            name="shopName"
            rules={[{ required: true, message: "请输入名称" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="shopType"
            label="类型"
            rules={[{ required: true, message: "请选择类型" }]}
          >
            <Select options={typeOptions} />
          </Form.Item>
          <Form.Item label="手机号" name="shopTel">
            <Input />
          </Form.Item>
          <Form.Item label="地址" name="shopAddress">
            <Input />
          </Form.Item>
          <Form.Item label="描述" name="shopDescription">
            <Input />
          </Form.Item>
          <Form.Item 
            label="评分" 
            name="shopScore"
            rules={[{ required: true, message: "请选择评分" }]}
          >
            <Select
              placeholder="请选择评分"
              options={[
                { label: <StarRating score={1} size={14} />, value: "1" },
                { label: <StarRating score={2} size={14} />, value: "2" },
                { label: <StarRating score={3} size={14} />, value: "3" },
                { label: <StarRating score={4} size={14} />, value: "4" },
                { label: <StarRating score={5} size={14} />, value: "5" }
              ]}
            />
          </Form.Item>
          <Form.Item 
            label="销售量" 
            name="shopSellCount"
            rules={[{ required: true, message: "请输入销售量" }]}
          >
            <Input placeholder="请输入销售量" />
          </Form.Item>
          <Form.Item label="商铺图片" name="shopImage">
            <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
              {imagePreview && (
                <div style={{ position: 'relative', display: 'inline-block' }}>
                  <img 
                    src={imagePreview} 
                    alt="预览" 
                    style={{ 
                      width: 120, 
                      height: 120, 
                      objectFit: 'cover',
                      borderRadius: '4px',
                      border: '1px solid #d9d9d9'
                    }}
                  />
                  <Button
                    type="text"
                    danger
                    size="small"
                    style={{
                      position: 'absolute',
                      top: 4,
                      right: 4,
                      background: 'rgba(0,0,0,0.6)',
                      color: 'white',
                      border: 'none',
                      borderRadius: '50%',
                      width: 20,
                      height: 20,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      padding: 0
                    }}
                    onClick={removeImage}
                  >
                    ✕
                  </Button>
                </div>
              )}
              <Space>
                <Button 
                  type="primary" 
                  onClick={() => {
                    const input = document.createElement('input');
                    input.type = 'file';
                    input.accept = 'image/*';
                    input.onchange = (e) => {
                      const target = e.target as HTMLInputElement;
                      if (target.files && target.files[0]) {
                        const file = target.files[0];
                        console.log('选择的文件:', file); // 调试用
                        
                        if (file.type.startsWith('image/')) {
                          // 检查文件大小（限制为5MB）
                          if (file.size > 5 * 1024 * 1024) {
                            message.error('图片大小不能超过5MB');
                            return;
                          }
                          
                          const reader = new FileReader();
                          reader.onload = (event) => {
                            const imageUrl = event.target?.result as string;
                            console.log('图片URL生成成功'); // 调试用
                            setImagePreview(imageUrl);
                            editForm.setFieldValue('shopImage', imageUrl);
                            message.success('图片上传成功');
                          };
                          reader.onerror = () => {
                            message.error('图片读取失败');
                          };
                          reader.readAsDataURL(file);
                        } else {
                          message.error('请选择图片文件');
                        }
                      }
                    };
                    input.click();
                  }}
                >
                  上传图片
                </Button>
                {imagePreview && (
                  <Button onClick={removeImage}>
                    移除图片
                  </Button>
                )}
              </Space>
              {/* 隐藏的输入框，确保图片数据能正确传递 */}
              <input 
                type="hidden" 
                value={imagePreview || ''} 
                onChange={() => {}} 
              />
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Indexone;
